<template>
  <div class="app-container">
    <h2 style="text-align: center">发布新课程</h2>

    <el-steps
      :active="2"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="填写课程基本信息" />
      <el-step title="创建课程大纲" />
      <el-step title="确认发布" />
    </el-steps>

    <el-form label-width="120px">
      <el-button type="text" @click="openChapterDialog">添加章节</el-button>
      <!-- 添加和修改章节表单(点击添加章节按钮才会显示) -->
      <el-dialog
        :visible.sync="dialogChapterFormVisible"
        :title="addOrEditChapter"
      >
        <el-form :model="chapter" label-width="120px">
          <el-form-item label="章节标题">
            <el-input v-model="chapter.title" />
          </el-form-item>
          <el-form-item label="章节排序">
            <el-input-number
              v-model="chapter.sort"
              :min="0"
              controls-position="right"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogChapterFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveOrUpdateChapter"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <!-- 添加和修改课时表单 -->
      <el-dialog :visible.sync="dialogVideoFormVisible" :title="addOrEditVideo">
        <el-form :model="video" label-width="120px">
          <el-form-item label="课时标题">
            <el-input v-model="video.title" />
          </el-form-item>
          <el-form-item label="课时排序">
            <el-input-number
              v-model="video.sort"
              :min="0"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="是否免费">
            <el-radio-group v-model="video.isFree">
              <el-radio :label="true">免费</el-radio>
              <el-radio :label="false">默认</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 上传视频 -->
          <el-form-item label="上传视频">
            <el-upload
              :on-success="handleVodUploadSuccess"
              :on-remove="handleVodRemove"
              :before-remove="beforeVodRemove"
              :on-exceed="handleUploadExceed"
              :file-list="fileList"
              :action="BASE_API + '/eduvod/video/uploadVideo'"
              :limit="1"
              class="upload-demo"
            >
              <el-button size="small" type="primary">上传视频</el-button>
              <el-tooltip placement="right-end">
                <div slot="content">
                  最大支持1G，<br />
                  支持3GP、ASF、AVI、DAT、DV、FLV、F4V、<br />
                  GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、<br />
                  MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、<br />
                  SWF、TS、VOB、WMV、WEBM 等视频格式上传
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVideoFormVisible = false">取 消</el-button>
          <el-button
            :disabled="saveVideoBtnDisabled"
            type="primary"
            @click="saveOrUpdateVideo"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <!-- 章节 -->
      <ul class="chanpterList">
        <li v-for="chapter in chapterVideoList" :key="chapter.id">
          <p>
            {{ chapter.title }}

            <span class="acts">
              <el-button type="text" @click="openVideo(chapter.id)"
                >添加课时</el-button
              >
              <el-button
                style=""
                type="text"
                @click="openEditChapter(chapter.id)"
                >编辑</el-button
              >
              <el-button type="text" @click="deleteChapter(chapter.id)"
                >删除</el-button
              >
            </span>
          </p>

          <!-- 视频 -->
          <ul class="chanpterList videoList">
            <li v-for="video in chapter.children" :key="video.id">
              <p>
                {{ video.title }}
                <span class="acts">
                  <el-button type="text" @click="openEditVideo(video.id)"
                    >编辑</el-button
                  >
                  <el-button type="text" @click="deleteVideo(video.id)"
                    >删除</el-button
                  >
                </span>
              </p>
            </li>
          </ul>
        </li>
      </ul>
      <div>
        <el-button @click="previous">上一步</el-button>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next"
          >下一步</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script>
import chapter from "@/api/edu/chapter";
import video from "@/api/edu/video";
import vod from "@/api/edu/vod";
export default {
  data() {
    return {
      saveBtnDisabled: false, // 保存按钮是否禁用
      saveVideoBtnDisabled: false, // 课时按钮是否禁用
      dialogChapterFormVisible: false, //是否显示章节表单
      dialogVideoFormVisible: false, // 是否显示课时表单
      chapterVideoList: [],
      courseId: "",
      chapterId: "", // 课时所在的章节id
      videoId: "",
      addOrEditChapter: "", //添加章节/修改章节
      addOrEditVideo: "",
      fileList: [], //上传文件列表
      BASE_API: process.env.BASE_API, // 接口API地址
      // 章节对象
      chapter: {
        title: "",
        sort: 0,
      },
      // 课时对象
      video: {
        title: "",
        sort: 0,
        free: 0,
        videoSourceId: "",
        videoOriginalName: "",
      },
    };
  },

  created() {
    //拿到链接中的courseId
    //如果网页链接中有参数 并且 参数名是id
    if (this.$route.params && this.$route.params.id) {
      this.courseId = this.$route.params.id;
      this.getChapterVideo();
    }
  },

  methods: {
    //以下方式存在问题，如果本身就有视频会误删！
    //小节修改点击取消时，消失弹框并且删除已上传的视频
    // dialogCancle() {
    //   this.dialogVideoFormVisible = false;
    //   if (
    //     this.video.videoSourceId != "") {
    //     //如果存在视频id则调用删除方法
    //     vod.deleteVo(this.video.videoSourceId);
    //     //清除视频id
    //     this.video.videoSourceId = "";
    //     //清除视频原始名称
    //     this.video.videoOriginalName = "";
    //     this.fileList = [];
    //     // video.updateSourceIdAndName(this.video.id);
    //   }
    // },
    //删除视频时提示信息
    beforeVodRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
    },
    //删除视频
    handleVodRemove() {
      //根据视频id删除视频
      vod.deleteVo(this.video.videoSourceId).then((response) => {
        //删除视频后还需要将数据库中的视频id和名字删除
        video.updateSourceIdAndName(this.video.id);
        this.$message({
          type: "success",
          message: "删除视频成功！",
        });      
        //清除相关数据，在确认修改时会对数据库内对应数据清空
        //清除视频id
        this.video.videoSourceId = "";
        //清除视频原始名称
        this.video.videoOriginalName = "";
        this.fileList = [];
      });
    },
    //成功回调
    handleVodUploadSuccess(response, file, fileList) {
      //设置视频id
      this.video.videoSourceId = response.data.videoId;
      //设置视频原始名称
      this.video.videoOriginalName = file.name;
    },
    //视图上传多于一个视频
    handleUploadExceed(files, fileList) {
      this.$message.warning("想要重新上传视频，请先删除已上传的视频");
    },
    //上一步
    previous() {
      this.$router.push({ path: "/edu/course/info/" + this.courseId });
    },
    //下一步
    next() {
      this.$router.push({ path: "/edu/course/publish/" + this.courseId });
    },
    // 根据id获取课程基本信息
    getChapterVideo() {
      chapter.getAllChapterVideo(this.courseId).then((response) => {
        this.chapterVideoList = response.data.chapterVos;
      });
    },
    //========================课时(小节)操作========================
    //点击添加课时按钮
    openVideo(chapterId) {
      this.addOrEditVideo = "添加课时";
      this.dialogVideoFormVisible = true;
      //注意：传入的chapterId是通过方法得到的数据中的chapter.id，而不是上面data中定义的chapterId(是空串)
      this.video.chapterId = chapterId;
      //弹框后需要清除框内数据
      this.video.title = "";
      this.video.sort = 0;
      this.video.free = 0;
      this.video.videoSourceId = "";
    },
    //保存课时
    saveVideo() {
      //需要章节id和课程id才能添加课时,给video中的chapterId、courseId赋值
      this.video.courseId = this.courseId;
      video
        .addVideo(this.video)
        .then((response) => {
          //隐藏弹框
          this.dialogVideoFormVisible = false;
          this.$message({
            type: "success",
            message: "添加课时成功!",
          });
          //保存成功后重新获取课程基本信息(刷新页面)
          this.getChapterVideo();
          // this.getVideoInfo();
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: response.message,
          });
        });
    },
    updateVideo() {
      //隐藏弹框
      this.dialogVideoFormVisible = false;
      video
        .updateVideo(this.video)
        .then((response) => {
          this.$message({
            type: "success",
            message: "修改课时成功!",
          });
          //修改成功后重新获取课程基本信息(刷新页面)
          this.getChapterVideo();
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: response.message,
          });
        });
    },
    //点击编辑按钮时，数据回显
    openEditVideo(videoId) {
      //将弹框左上角文本修改成 修改章节
      this.addOrEditVideo = "修改课时";
      //显示弹框
      this.dialogVideoFormVisible = true;
      //根据章节id重新获取章节信息
      video.getVideoInfo(videoId).then((response) => {
        this.video = response.data.videoInfo;
        if(this.video.videoOriginalName != ""){
          this.fileList = [{ name: this.video.videoOriginalName }];
        }
      });
    },
    //确认按钮,判断执行添加章节还是修改章节
    saveOrUpdateVideo() {
      //根据addOrEditVideo是添加章节还是修改章节来判断执行的方法
      //视频中使用的是是否存在课程id，但是如果添加过一次章节就会存在课程id，导致只能添加一次章节(也可以在openChapterDialog方法中设置id='';)
      if (this.addOrEditVideo === "添加课时") {
        this.saveVideo();
      } else {
        this.updateVideo();
      }
    },
    //删除课时
    deleteVideo(videoId) {
      this.$confirm("是否删除本课时?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return video.deleteVideo(videoId);
        })
        .then(() => {
          this.getChapterVideo(); // 重新获取课程信息(刷新列表)
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((response) => {
          // 失败
          if (response === "cancel") {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          } else {
            this.$message({
              type: "error",
              message: response.message,
            });
          }
        });
    },
    //========================章节操作========================
    //添加章节
    saveChapter() {
      //隐藏弹框
      this.dialogChapterFormVisible = false;
      //需要课程id才能添加章节,给chapter中的courseId赋值
      this.chapter.courseId = this.courseId;
      chapter
        .addChapter(this.chapter)
        .then((response) => {
          this.$message({
            type: "success",
            message: "添加章节成功!",
          });
          //保存成功后重新获取课程基本信息(刷新页面)
          this.getChapterVideo();
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: response.message,
          });
        });
    },
    //修改章节
    updateChapter() {
      //隐藏弹框
      this.dialogChapterFormVisible = false;
      chapter
        .updateChapter(this.chapter)
        .then((response) => {
          this.$message({
            type: "success",
            message: "修改章节成功!",
          });
          //修改成功后重新获取课程基本信息(刷新页面)
          this.getChapterVideo();
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: response.message,
          });
        });
    },
    //删除章节
    deleteChapter(chapterId) {
      this.$confirm("是否删除本章节?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return chapter.deleteChapter(chapterId);
        })
        .then(() => {
          this.getChapterVideo(); // 重新获取课程信息(刷新列表)
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((response) => {
          // 失败
          if (response === "cancel") {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          } else {
            this.$message({
              type: "error",
              message: response.message,
            });
          }
        });
    },
    //确认按钮,判断执行添加章节还是修改章节
    saveOrUpdateChapter() {
      //根据addOrEditChapter是添加章节还是修改章节来判断执行的方法
      //视频中使用的是是否存在课程id，但是如果添加过一次章节就会存在课程id，导致只能添加一次章节(也可以在openChapterDialog方法中设置id='';)
      if (this.addOrEditChapter === "添加章节") {
        this.saveChapter();
      } else {
        this.updateChapter();
      }
    },
    //点击编辑按钮时，数据回显
    openEditChapter(chapterId) {
      //将弹框左上角文本修改成 修改章节
      this.addOrEditChapter = "修改章节";
      //显示弹框
      this.dialogChapterFormVisible = true;
      //根据章节id重新获取章节信息
      chapter.getChapterInfo(chapterId).then((response) => {
        this.chapter = response.data.chapterInfo;
      });
    },
    //点击添加章节
    openChapterDialog() {
      //将弹框左上角文本修改成 添加章节
      this.addOrEditChapter = "添加章节";
      //显示弹框
      this.dialogChapterFormVisible = true;
      //清除弹框内的数据
      this.chapter.title = "";
      this.chapter.sort = 0;
    },
  },
};
</script>

<style scoped>
.chanpterList {
  position: relative;
  list-style: none;
  margin: 0;
  padding: 0;
}
.chanpterList li {
  position: relative;
}
.chanpterList p {
  float: left;
  font-size: 20px;
  margin: 10px 0;
  padding: 10px;
  height: 70px;
  line-height: 50px;
  width: 100%;
  border: 1px solid #ddd;
}
.chanpterList .acts {
  float: right;
  font-size: 14px;
}

.videoList {
  padding-left: 50px;
}
.videoList p {
  float: left;
  font-size: 14px;
  margin: 10px 0;
  padding: 10px;
  height: 50px;
  line-height: 30px;
  width: 100%;
  border: 1px dotted #ddd;
}
</style>